﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace doufu.Common
{
    public class IntegerAttribute : ValidationAttribute, IClientValidatable
    {
        // 服务端验证逻辑，判断输入是否为整型
        public override bool IsValid(object value)
        {
            var number = Convert.ToString(value);
            return Regex.IsMatch(number, @"^[0-9]+$");
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,

                // ValidationType - 指定一个 key（字符串），该 key 用于关联服务端验证逻辑与客户端验证逻辑。注：这个 key 必须都是由小写字母组成
                ValidationType = "isinteger"
            };

            // 向客户端验证代码传递参数
            rule.ValidationParameters.Add("param1", "value1");
            rule.ValidationParameters.Add("param2", "value2");

            yield return rule;
        }
    }
}